package com.kepus.web.interceptor;

import com.kepus.service.cache.LoginedUserCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by 巩聪 on 2018/6/14.
 */
public class LoginCheckInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginCheckInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //不存在不创建session

        HttpSession session = request.getSession(false);
        if (null == session) {
            LOGGER.info("ip: {} first access but no login page.", request.getRemoteAddr());
            return false;
        }
        String sessionId = session.getId();
        LoginedUserCache.UserCachedInfo userCachedInfo = LoginedUserCache.get(sessionId);
        if(null == userCachedInfo)
        {
            LOGGER.info("ip: {} login over time.", request.getRemoteAddr());
            return false;
        }
        return true;

    }
}
